package com.example.test.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Author: fxy
 * @Date: 2022/01/06/15:42
 * @Description:
 */
public class Demo2 {
    public static void main(String[] args) throws Exception {
        socketChannel();
    }

    public static void socket() throws Exception {
        int port = 8888;
        ByteBuffer buffer = ByteBuffer.wrap("hello wefrt".getBytes());
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(port));
        //非阻塞模式
        ssc.configureBlocking(false);
        while (true){
            SocketChannel sc = ssc.accept();
            if(sc==null){
                Thread.sleep(2000);
                System.out.println("null");
            }else {
                System.out.println(sc.socket().getRemoteSocketAddress());
                buffer.rewind();
                sc.write(buffer);
                sc.close();
            }
        }
    }

    public static void socketChannel() throws Exception {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("www.baidu.com",80));
        socketChannel.configureBlocking(true);
        ByteBuffer byteBuffer = ByteBuffer.allocate(48);
        socketChannel.read(byteBuffer);
        socketChannel.close();
        System.out.println("1");

    }

    public static void DatagramChannel() throws Exception {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("www.baidu.com",80));
        socketChannel.configureBlocking(true);
        ByteBuffer byteBuffer = ByteBuffer.allocate(48);
        socketChannel.read(byteBuffer);
        socketChannel.close();
        System.out.println("1");

    }

}
